package com.compass.mobile.ui.fragment

import UserInfoManager
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.fragment.app.activityViewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.leanback.widget.OnChildViewHolderSelectedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.compass.mobile.R
import com.compass.mobile.callback.OnInspectCallBack
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentIndependentBillingBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.INSPECT_CONFIRM
import com.compass.mobile.framework.constant.TEST_ACTION
import com.compass.mobile.framework.constant.TEST_ORDER_ACTION
import com.compass.mobile.framework.constant.YD_USER_TOKEN
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.BigDecimalUtils
import com.compass.mobile.framework.utils.CodeUtils.getCodeUrl
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.models.Attach
import com.compass.mobile.models.IndependentBillingBean
import com.compass.mobile.models.Title
import com.compass.mobile.presenters.BillingPresenter
import com.compass.mobile.ui.activity.MyInspectionActivity
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.dialog.CustomerServiceCode
import com.compass.mobile.ui.dialog.InspectSelectedOrderDialog
import com.compass.mobile.ui.viewModel.IndependentBillingViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import toJson


/**
 * Description： 自主开单--检验检查
 * Date:2024/5/22 10:20
 */
class IndependentBillingFragment : BaseVBFragment<FragmentIndependentBillingBinding>() {
    private lateinit var inspectFragment: InspectFragment
    private val independentBillingViewModel: IndependentBillingViewModel by activityViewModels()
    private var selectedInspectList: MutableList<IndependentBillingBean> = mutableListOf()//已选的集合
    private var inspectionIds: ArrayList<String> = ArrayList()//已选的集合id
    private lateinit var oderCodeDialog: CodeDialog.Builder
    override fun initView(view: View, savedInstanceState: Bundle?) {
        initCaseTitle()
        inspectFragment = InspectFragment()
        displaySelectedFragment(inspectFragment)

    }


    // 根据需要显示或替换Fragment
    private fun displaySelectedFragment(fragment: Fragment) {
        val fragmentTransaction: FragmentTransaction = childFragmentManager.beginTransaction()
        fragmentTransaction.add(R.id.fragmentChild, fragment)
        fragmentTransaction.commit()
    }

    override fun initData() {
        independentBillingViewModel.selectedListLiveData.observe(this) {

            calculatedAmount(it)

        }


        LiveDataBus.get().with(TEST_ORDER_ACTION, Attach::class.java)
            .observe(this) {
                if (::oderCodeDialog.isInitialized) {
                    oderCodeDialog.dismissDialog()
                }
                CustomerServiceCode.Builder(requireActivity(), TEST_ACTION).show()
            }

        LiveDataBus.get().with(TEST_ACTION,Attach::class.java)
            .observe(this) {
                if (::oderCodeDialog.isInitialized) {
                    oderCodeDialog.dismissDialog()
                }
                CustomerServiceCode.Builder(requireActivity(), TEST_ACTION).show()
            }

    }


    /**
     * 计算金额
     */
    private var drugsCost = "0"
    private fun calculatedAmount(list: MutableList<IndependentBillingBean>) {
        selectedInspectList = list
        drugsCost = "0"
        inspectionIds.clear()
        for (item in list) {
            inspectionIds.add(item.id)
            item.price.let {
                drugsCost = BigDecimalUtils.add(it, drugsCost, 2)
            }
        }

        mBinding?.tvInfo?.text = "已选${selectedInspectList.size}项  共计:￥${drugsCost}"

    }


    private var onInspectCallBack: OnInspectCallBack = object : OnInspectCallBack {
        override fun onInspectCallBack(
            type: String,
            selectedInspects: MutableList<IndependentBillingBean>
        ) {

            when (type) {
                "delete" -> {
                    calculatedAmount(selectedInspects)
                }

                "submit" -> {
                    if (selectedInspects.isNotEmpty()) {
                        UserInfoManager.getPatientInfo()?.id?.let {
                            oderCodeDialog = CodeDialog.Builder(
                                requireActivity(),
                                INSPECT_CONFIRM + "${getCodeUrl()}&ids=${inspectionIds.toJson()}"
                            )
                            oderCodeDialog.show()
                        }
                    } else {
                        showToast("您还没有选择检验检查项目")
                    }
                }
            }

        }
    }


    override fun intListener() {
        mBinding?.tvSelected?.onClick {
            if(selectedInspectList.size>0){
                val inspectSelectedOrderDialog =
                    InspectSelectedOrderDialog.Builder(
                        requireActivity(),
                        selectedInspectList,
                        onInspectCallBack
                    )
                inspectSelectedOrderDialog.show()
            }else{
                showToast("您还没有添加检验检查")
            }

        }
        mBinding?.tvSubmit?.onClick {
            MyInspectionActivity.start(requireContext())
        }
    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {

        }
    }


    // 保存上一个选中的位置 实现高亮显示效果
    var lastSelectedPosition: Int = -1
    private val onChildViewHolderSelectedListener: OnChildViewHolderSelectedListener = object :
        OnChildViewHolderSelectedListener() {
        override fun onChildViewHolderSelected(
            parent: RecyclerView?,
            childViewHolder: RecyclerView.ViewHolder?,
            position: Int,
            subposition: Int
        ) {
            childViewHolder?.itemView?.setBackgroundResource(R.drawable.case_focus)
            if (lastSelectedPosition!=-1){
                var lastViewHolder=parent?.findViewHolderForAdapterPosition(lastSelectedPosition)
                lastViewHolder?.itemView?.setBackgroundResource(R.drawable.case_title_selector)
            }
            lastSelectedPosition=position
            when (position) {
                0 -> {
                    inspectFragment.showLoading()
                    independentBillingViewModel.getInspectionList("1")
                }

                else -> {
                    inspectFragment.showLoading()
                    independentBillingViewModel.getInspectionList("2")
                }
            }
        }
    }

    @SuppressLint("RestrictedApi")
    fun initCaseTitle() {
        val arrayObjectAdapter = ArrayObjectAdapter(BillingPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )
        mBinding?.gridCase?.setAdapter(itemBridgeAdapter)
        arrayObjectAdapter.addAll(0, titleList)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_SMALL, false
        )
        mBinding?.gridCase?.setOnChildViewHolderSelectedListener(onChildViewHolderSelectedListener)
        mBinding?.gridCase?.requestFocus()
        lifecycleScope.launch {
            delay(500)
            //延迟获取焦点
            mBinding?.gridCase?.requestFocus()
        }

    }


    companion object {
        //模拟数据
        val titleList: List<Title?>
            get() {
                val titleList: MutableList<Title?> = ArrayList()
                titleList.add(Title("检验"))
                titleList.add(Title("检查"))
                return titleList
            }


    }
}
